package com.aw.puzzle.dropboxdiet;

import com.aw.puzzle.dropboxdiet.support.CombinationsLogger;

import java.util.List;

/**
 * User: gmc
 * Date: 29/01/11
 */
public class SequentialGroupProvider extends AbstractActivityGroupProvider {
    private GroupConfigInfo currentGroupConfigInfo;

    public SequentialGroupProvider(List<Activity> activities) {
        super(activities);
        init();
    }

    public void refresh(List<Activity> activities) {
        this.activities = activities;
        init();
    }

    private void init() {
        currentGroupConfigInfo = new GroupConfigInfo(1);
    }

    public ActivityGroup getNextGroup() {
        ActivityGroup nextGroup = currentGroupConfigInfo.nextGroup();
        if (nextGroup == null) {
            int activitiesXGroup = currentGroupConfigInfo.activitiesXGroup + 1;
            if (activitiesXGroup > activities.size()) {
                return null;
            }
            currentGroupConfigInfo = new GroupConfigInfo(activitiesXGroup);
            nextGroup = currentGroupConfigInfo.nextGroup();
        }
        return nextGroup;
    }

    public ActivityGroup getNextGroupWithValueLessThan(int value) {
        ActivityGroup nextActivityGroup;
        do {
            nextActivityGroup = getNextGroup();
        } while (nextActivityGroup != null && nextActivityGroup.getValue() > value);
        return nextActivityGroup;
    }


    private class GroupConfigInfo {
        private int activitiesXGroup;
        private int[] lastCombination;

        private GroupConfigInfo(int activitiesXGroup) {
            this.activitiesXGroup = activitiesXGroup;
        }

        public ActivityGroup nextGroup() {
            int[] newCombination = getNewCombination();
            CombinationsLogger.log("Sequential List", newCombination);
            if (newCombination != null) {
                ActivityGroup newGroup = getNewGroupBasedOn(newCombination);
                lastCombination = newCombination;
                return newGroup;
            }
            return null;
        }

        private int[] getNewCombination() {
            if (lastCombination == null) {
                return combinationsGenerator.getFirstCombinationOfSize(activitiesXGroup);
            }
            return combinationsGenerator.getNextCombination(activities.size(), lastCombination);
        }
    }
}
